package com.aitesting.common;

import cn.hutool.core.text.csv.CsvData;
import cn.hutool.core.text.csv.CsvReadConfig;
import cn.hutool.core.text.csv.CsvReader;
import cn.hutool.core.text.csv.CsvRow;
import lombok.extern.slf4j.Slf4j;
import org.yaml.snakeyaml.Yaml;
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Slf4j
public class Loader {

    public static List<Map<String, String>> load_csv_file(String csv_file){
        CsvReadConfig config = CsvReadConfig.defaultConfig();
        config.setContainsHeader(true);
        File file = new File(csv_file);//暂时只支持绝对路径
        CsvReader reader = new CsvReader(config);
        CsvData csvData = reader.read(file);
        List<Map<String, String>> csv_content_list = new ArrayList<>();
        for(CsvRow row:csvData.getRows()){
            System.out.println(row.getFieldMap());
            csv_content_list.add(row.getFieldMap());
        }
        return csv_content_list;
    }
    /**
     * 加载测试用例文件
     * @param test_file json或者yaml文件
     * @return 测试用例
     */
    public static Map<String,Object> load_testcase_file(String test_file){
        String file_suffix = test_file.substring(test_file.lastIndexOf(".") + 1);
        System.out.println(file_suffix);
        Map<String, Object> test_file_content = null;
        if(file_suffix.equals("yaml") || file_suffix.equals("yml")){
            test_file_content = load_yaml_file(test_file);
        }else if(file_suffix.equals("json")){
            test_file_content = load_json_file(test_file);
        }
        return test_file_content;
    }

    public static Map<String, Object> load_json_file(String json_file){
        return null;
    }

    public static <T> Map<String, Object> load_yaml_file(String yaml_file){
        Yaml yaml = new Yaml();
        T result = null;
        try (FileInputStream in = new FileInputStream(yaml_file)) {
            result = yaml.load(in);
        } catch (Exception ignored) {}
        return  (Map<String, Object>) result;
    }

    public static void main(String[] args) {
        String path = "D:\\IdeaProjects\\aitesting-macroservice\\aitesting-apirunner\\src\\main\\java\\com\\aitesting\\testcase.yml";
        Map<String, Object> map = Loader.load_testcase_file(path);
        System.out.println(map.toString());
    }
}
